#! /usr/bin
#coding=utf-8

import cv2
import rospy
from aip import AipSpeech 
import os 
from std_msgs.msg import String

""" 你的 APPID AK SK """
APP_ID = '16425806'  
API_KEY = 'Lz5VMGB5qufER9kxiik0IR1a'
SECRET_KEY = 'EgGkUUHWHLtkkYG2GIpAswG9hK7hOzMH'
client = AipSpeech(APP_ID,API_KEY,SECRET_KEY) 
rospy.init_node('ttsplay', anonymous=False)
ttsdata=String()
old_data=''
def callback(data):
    global old_data
    new_data=data.data
    if new_data != old_data:
		cmd="play ~/Desktop/show_demo/mp3/"+str(new_data)+'.mp3'
		print(cmd)
		ok=os.system(cmd)
		if ok==512:
			try:
				result= client.synthesis(data.data, 'zh', 1, {
				'spd': 4,    #语速 0最小 9最大
				'pit': 6,    #音调 0最小 9最大   
				'vol': 14    #音量 0最小 15最大
				})

				if not isinstance(result, dict):
					file_name = 'auido.mp3'      
					with open(file_name, 'wb') as f:  
						f.write(result) 
					os.system('play auido.mp3')
			except:
				os.system("play ~/Desktop/show_demo/mp3/net.mp3")
		old_data=new_data

def get_string():
    rospy.Subscriber("tts_topic" , String , callback,queue_size=1)
    rospy.spin()

if __name__ == '__main__':
    print("语音合成节点启动")
    try:
        get_string()
    except rospy.ROSInterruptException:
        rospy.loginfo("tts node terminated.")

    


